<?php
namespace control;
//管理员后台-收发明细表
class receiptDeliveryClass extends adIndexClass
{
	private const title       = '收发明细表';
	private const page        = 'receiptDelivery';
	private const table       = 'inventory_detail';
	private const tableRecord = 'inventory_record';
    private const optType     = ['销售发货','销售退货','采购收货','采购退货', '生产领料',  '生产退料', '生产入库','其他出库','其他入库', '配料出库','委外收货','委外退货','委外领料','委外退料','线边库存退库', '报废入库'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'code'          => [
                        'name'  => '{l.receiptDelivery.home.code}',
                        'width' => 150,
                    ],
                    'name' => [
                        'name'  => '{l.receiptDelivery.home.materialName}',
                        'width' => 150,
                    ],
                    'typeName'  => [
                        'name'  => '{l.receiptDelivery.home.materialType}',
                        'width' => 150,
                    ],
                    'model'  => [
                        'name'  => '{l.receiptDelivery.home.model}',
                        'width' => 150,
                    ],
                    'unit'  => [
                        'name'  => '{l.receiptDelivery.home.unit}',
                        'width' => 60,
                    ],
                    'time'         => [
                        'name'  => '出入库日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'orderNo'          => [
                        'name'  => '{l.receiptDelivery.home.orderNo}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => '{l.receiptDelivery.home.type}',
                        'width' => 100,
                    ],
                    'target'          => [
                        'name'  => '{l.receiptDelivery.home.target}',
                        'width' => 150,
                    ],
                    'warehouseId'          => [
                        'name'  => '{l.receiptDelivery.home.warehouse}',
                        'width' => 100,
                    ],
                    'inNum'          => [
                        'name'  => '{l.receiptDelivery.home.inNum}',
                        'width' => 100,
                    ],
                    'inBatch'          => [
                        'name'  => '{l.receiptDelivery.home.inBatch}',
                        'width' => 200,
                    ],
                    'inPrice'          => [
                        'name'  => '{l.receiptDelivery.home.inPrice}',
                        'width' => 100,
                    ],
                    'inTotal'          => [
                        'name'  => '{l.receiptDelivery.home.inTotal}',
                        'width' => 100,
                    ],
                    'outNum'          => [
                        'name'  => '{l.receiptDelivery.home.outNum}',
                        'width' => 100,
                    ],
                    'outBatch'          => [
                        'name'  => '{l.receiptDelivery.home.outBatch}',
                        'width' => 200,
                    ],
                    'outPrice'          => [
                        'name'  => '{l.receiptDelivery.home.outPrice}',
                        'width' => 100,
                    ],
                    'outTotal'          => [
                        'name'  => '{l.receiptDelivery.home.outTotal}',
                        'width' => 100,
                    ],
                    'inventoryNum'          => [
                        'name'  => '{l.receiptDelivery.home.inventoryNum}',
                        'width' => 100,
                    ],
                    'inventoryPrice'          => [
                        'name'  => '{l.receiptDelivery.home.inventoryPrice}',
                        'width' => 100,
                    ],
                    'inventoryMoney'          => [
                        'name'  => '{l.receiptDelivery.home.inventoryMoney}',
                        'width' => 100,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('receiptDelivery.home.code')   => text(array("name" => "code")),
                    L('receiptDelivery.home.materialName') => text(array("name" => "name")),
                    L('inventoryDistribution.home.type') => materialClass::typeSelect(name: 'typeId',title: '请选择'),
                ],
                [
                    L('receiptDelivery.home.orderDate') => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date']]),
                    L('receiptDelivery.home.orderNo') => text(["name" => "orderNo"]),
                    L('receiptDelivery.home.type') => text(["name" => "type"]),
                ],
                [
                    L('receiptDelivery.home.target') => text(["name" => "targetName"]),
                    L('receiptDelivery.home.batch') => text(["name" => "batch"]),
                    L('receiptDelivery.home.warehouse') => selectMultiple([
                        'table' => 'warehouse',
                        'sqlField' => 'name',
                        'sqlId' => 'id',
                        'where' => "coid = '" . self::$coid . "' AND state = '启用' ".self::getWarehouseSql(),
                        'name' => 'warehouseId',
                        'class' => 'width200',
                    ]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*列表页-查询结果*/
	public function homeSearch()
	{
		//查询结果
		$where = " d.coid = '" . self::$coid . "' AND i.id = d.orderId AND i.state in ('已入库', '已出库', '已复核') ";
		// 物料条件
		$mwhere = search([
			"="    => [
			],
			"like" => [
                'code' => $this->post('code'),
                'name' => $this->post('name'),
                'typeName' => $this->post('typeId'),
			],
		]);
		if ($mwhere) {
			$where .= " AND d.materialId in (SELECT id FROM material WHERE 1=1 {$mwhere}  )  ";
		}
		$equal = [
		];
		$like  = [
			'd.warehouseId' => $this->post('warehouseId'),
            'i.type'    => $this->post('type'),
            'i.orderNo' => $this->post('orderNo'),
            'd.batch' => $this->post('batch'),
		];
		$where .= self::getWarehouseSql('d.warehouseId');
		if ($this->post('targetName')) {
			$where .= " AND (targetId IN (SELECT id FROM supplier WHERE coid = '" . self::$coid . "' AND name LIKE '%{$this->post('targetName')}%') or targetId IN (SELECT khid FROM kehu WHERE coid = '" . self::$coid . "' AND companyName LIKE '%{$this->post('targetName')}%') )";
		}
        /*if ($this->post('batch')) {
            $where .= " AND d.id IN (SELECT inventoryMxId FROM inventory_record WHERE coid = '" . self::$coid . "' AND batch LIKE '%{$this->post('batch')}%')";
        }*/
		//生成查询语句
		$where .= search([
			"="    => $equal,
			"like" => $like,
		]);
		if ($this->post('orderDate')) {
			$where .= self::timeComparison($this->post('orderDate'), 'date', 'i.confirmTime');
		}
		$totalWhere = $where;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page                        = $this->page([
		    "table" => " inventory_changes_detail as d join inventory_changes as i on i.id = d.orderId",
            'field' => ' d.`id`, d.`orderId`, i.`confirmTime` as time, d.`materialId`, d.`orderNum`, d.`num`, d.`unit`, d.`price`, d.`sourceId`, d.`warehouseId`, d.`text`, d.`list`, d.`batch`, i.`targetId`, i.`orderNo`, `classify`, i.`type`, i.`text` ',
            "where" => $where,
            "order" => $orderBy['orderBy']
        ]);
		$json['sql'] = $page['sql'];
		$_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
			$material     = query('material', " id = '$array[materialId]'");
			// 入库
			if ($array['classify'] == 1) {
                $inNum = $array['num'];
				$inPrice = $array['price'];
				$inTotal = self::formattingFigure($inNum * $inPrice);
				$inBatch = "<span title='{$array['batch']}' class='batchText'>{$array['batch']}</span>";
				$outNum  = $outPrice = $outTotal = $outBatch = '';
			} else {
                $outNum = $array['num'];
				$inNum    = $inPrice = $inTotal =  $inBatch = '';
				$outPrice = $array['price'];
                $outBatch = "<span title='{$array['batch']}' class='batchText'>{$array['batch']}</span>";
				$outTotal = self::formattingFigure($outNum * $outPrice);
			}
			$inventoryNum   = inventoryBalanceClass::inventoryNum($array['materialId'], $array['warehouseId']);
			$inventoryPrice = inventoryBalanceClass::unitPrice($material['id']);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'time':
                        $row[] = self::formatDate($array['time']);
                        break;
                    case 'warehouseId':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'target':
                        $target       = query('kehu', " khid = '$array[targetId]' ")['companyName'];
                        if (empty($target)) {
                            $target = query('supplier', " id = '$array[targetId]' ")['name'];
                        }
                        $row[] = $target;
                        break;
                    case 'code':
                    case 'name':
                    case 'typeName':
                    case 'model':
                    case 'unit':
                    case 'unit_one':
                    case 'unit_two':
                        $row[] = $material[$key];
                        break;
                    case 'inNum':
                        $row[] = self::lostZero($inNum,'numPrecision');
                        break;
                    case 'inBatch':
                        $row[] = $inBatch;
                        break;
                    case 'inPrice':
                        $row[] = self::lostZero($inPrice,'pricePrecision');
                        break;
                    case 'inTotal':
                        $row[] = self::lostZero($inTotal);
                        break;
                    case 'outNum':
                        $row[] = self::lostZero($outNum,'numPrecision');
                        break;
                    case 'outBatch':
                        $row[] = $outBatch;
                        break;
                    case 'outPrice':
                        $row[] = self::lostZero($outPrice,'pricePrecision');
                        break;
                    case 'outTotal':
                        $row[] = self::lostZero($outTotal);
                        break;
                    case 'inventoryNum':
                        $row[] = self::lostZero($inventoryNum,'numPrecision');
                        break;
                    case 'inventoryPrice':
                        $row[] = self::lostZero($inventoryPrice,'pricePrecision');
                        break;
                    case 'inventoryMoney':
                        $row[] = self::formattingFigure($inventoryNum * $inventoryPrice);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //发货出库金额
        $out_cost = find(array(
            "table"=>" inventory_changes_detail as d join inventory_changes as i on d.orderId = i.id ",
            "field"=>" ifnull(sum(d.num),0) as num,ifnull(sum(d.money),0) as money ",
            "single"=>"  {$totalWhere} and i.classify = 0 "
        ));
        //退货入库金额
        $in_cost = find(array(
            "table"=>" inventory_changes_detail as d join inventory_changes as i on d.orderId = i.id ",
            "field"=>" ifnull(sum(d.num),0) as num,ifnull(sum(d.money),0) as money ",
            "single"=>" {$totalWhere} and i.classify = 1 "
        ));
        /*$button.=saleIncomeClass::titleSpan('入库数量合计',self::formattingFigure($in_cost['num']));
        $button.=saleIncomeClass::titleSpan('入库金额合计',self::formattingFigure($in_cost['money']));
        $button.=saleIncomeClass::titleSpan('出库数量合计',self::formattingFigure($out_cost['num']));
        $button.=saleIncomeClass::titleSpan('出库金额合计',self::formattingFigure($out_cost['money']));*/
        $total = [
            'inNum' => self::formattingFigure($in_cost['num']),
            'inTotal' => self::formattingFigure($in_cost['money']),
            'outNum' => self::formattingFigure($out_cost['num']),
            'outTotal' => self::formattingFigure($out_cost['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total" => $total,
        ));
		//返回
		$json['html'] = $page['hint'] .
            $button .
            "<style>.batchText{overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 1;}</style>
            <form name='listForm'>" . $li . "</form>" .
            $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 导出
	 */
	public function exportData()
	{
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => " inventory_changes_detail as d join inventory_changes as i on i.id = d.orderId",
                    'field' => ' d.`id`, d.`orderId`, i.`confirmTime` as time, d.`materialId`, d.`orderNum`, d.`num`, d.`unit`, d.`price`, d.`sourceId`, d.`warehouseId`, d.`text`, d.`list`, d.`batch`, i.`targetId`, i.`orderNo`, `classify`, i.`type` ',
                    "where" => "d.id in ('".implode("','", $checkedId)."') order by i.`confirmTime` desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $material     = query('material', " id = '$array[materialId]'");
                $target       = query('kehu', " khid = '$array[targetId]' ")['companyName'];
                if (empty($target)) {
                    $target = query('supplier', " id = '$array[targetId]' ")['name'];
                }
                // 入库
                if ($array['classify'] == 1) {
                    $inNum   = $array['num'];
                    $inPrice = $array['price'];
                    $inBatch = $array['batch'];
                    $inTotal = $inNum * $inPrice;
                    $outNum  = $outPrice = $outTotal = $outBatch = '';
                } else {
                    $inNum    = $inPrice = $inTotal = $inBatch = '';
                    $outNum   = $array['num'];
                    $outPrice = $array['price'];
                    $outBatch = $array['batch'];
                    $outTotal = $outNum * $outPrice;
                }
                $inventoryNum   = inventoryBalanceClass::inventoryNum($array['materialId'], $array['warehouseId']);
                $inventoryPrice = inventoryBalanceClass::unitPrice($material['id']);
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '物料编码'=> $material['code'],
                            '物料名称'=> $material['name'],
                            '物料分类'=> $material['typeName'],
                            '规格型号'=> $material['model'],
                            '主单位'=> $material['unit'],
                            '日期'=> self::formatDate($array['time']),
                            '单据编号'=>$array['orderNo'],
                            '业务类型'=>$array['type'],
                            '往来单位'=>$target,
                            '仓库'=>warehouseClass::getName($array['warehouseId']),
                            '入库数量'=> self::lostZero($inNum,'numPrecision'),
                            '入库批号明细'=>  $inBatch,
                            '入库单价'=> self::lostZero($inPrice,'pricePrecision'),
                            '入库金额'=> self::lostZero($inTotal),
                            '出库数量'=>self::lostZero($outNum,'numPrecision'),
                            '出库批号明细'=> $outBatch,
                            '出库单价'=>  self::lostZero($outPrice,'pricePrecision'),
                            '出库金额'=> self::lostZero($outTotal),
                            '库存数量'=> self::lostZero($inventoryNum,'numPrecision'),
                            '库存单价'=>self::lostZero($inventoryPrice,'pricePrecision'),
                            '库存金额'=> self::formattingFigure($inventoryNum * $inventoryPrice),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
			$text = str_replace(['{{staffName}}'], [$this->control['name']], L('receiptDelivery.exportData.log'));
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, L('receiptDelivery.exportData.fileName') . ".xlsx");
            exit(0);
        }
		header("Location:" . getenv("HTTP_REFERER"));
	}
    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'物料分类',
                    'aliasName'=>'物料分类',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'主单位',
                    'aliasName'=>'主单位',
                ],
                [
                    'columnName'=>'日期',
                    'aliasName'=>'日期',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'业务类型',
                    'aliasName'=>'业务类型',
                ],
                [
                    'columnName'=>'往来单位',
                    'aliasName'=>'往来单位',
                ],
                [
                    'columnName'=>'仓库',
                    'aliasName'=>'仓库',
                ],
                [
                    'columnName'=>'入库数量',
                    'aliasName'=>'入库数量',
                ],
                [
                    'columnName'=>'入库批号明细',
                    'aliasName'=>'入库批号明细',
                ],
                [
                    'columnName'=>'入库单价',
                    'aliasName'=>'入库单价',
                ],
                [
                    'columnName'=>'入库金额',
                    'aliasName'=>'入库金额',
                ],
                [
                    'columnName'=>'出库数量',
                    'aliasName'=>'出库数量',
                ],
                [
                    'columnName'=>'出库批号明细',
                    'aliasName'=>'出库批号明细',
                ],
                [
                    'columnName'=>'出库单价',
                    'aliasName'=>'出库单价',
                ],
                [
                    'columnName'=>'出库金额',
                    'aliasName'=>'出库金额',
                ],
                [
                    'columnName'=>'库存数量',
                    'aliasName'=>'库存数量',
                ],
                [
                    'columnName'=>'库存单价',
                    'aliasName'=>'库存单价',
                ],
                [
                    'columnName'=>'库存金额',
                    'aliasName'=>'库存金额',
                ],
            ]
        };
    }
}
